package top.codedance.iotp.client.manage.net.handler.taskHandler;

import cd.io.netty.channel.ChannelHandlerContext;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.client.manage.ManageApplication;
import top.codedance.iotp.client.manage.net.listenner.TaskExecuter;
import top.codedance.iotp.common.constent.Command;
import top.codedance.iotp.common.entity.CommonEntity;
import org.apache.log4j.Logger;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class UpdateExecuterImpl implements TaskExecuter {
    private static Logger logger = ManageApplication.getLogger(UpdateExecuterImpl.class);

    @Override
    public void exec(ChannelHandlerContext channelHandlerContext, byte[] data, String taskId) {
        if(!ManageApplication.isUpgrading()) {
            try {
                String versionStr = new String(data, StandardCharsets.UTF_8);
                CommonEntity commonEntity = new CommonEntity();
                commonEntity.setCommand(Command.DOWNLOAD);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("taskId", UUID.randomUUID());
                jsonObject.put("version", versionStr);
                commonEntity.setBody(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8));
                channelHandlerContext.writeAndFlush(commonEntity);
                ManageApplication.startUpgrade();
            } catch (Exception e) {
                logger.debug(e.getMessage());
            }
        }
    }
}
